package com.mooc.swxy.tool;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author Siaze
 * @date 2022/4/19
 */
@Component
public class RequestTool {

    private RestTemplate restTemplate;

    public RequestTool(){
        this.restTemplate = new RestTemplate();
    }

    /**
     * @param url url
     * @param clazz 返回类型
     * @param <T> 返回类型
     * @return 请求的返回数据
     */
    public <T> T getForObject(String url, Class<T> clazz) {
        return restTemplate.getForObject(url, clazz);
    }

    /**
     * @param url url
     * @param clazz 返回类型
     * @return  返回请求
     */
    public <T> ResponseEntity<T> getForEntity(String url, Class<T> clazz) {
        return restTemplate.getForEntity(url, clazz);
    }

    public <T> T postRequest(String url, MediaType mediaType, Map<String,String> params,String token, Class<T> clazz) {
        HttpHeaders headers = new HttpHeaders();
        if (token != null) {
            headers.add("Cookie", "token=" + token);
        }
        headers.setContentType(mediaType);
        headers.add("connection","Keep-Alive");
        headers.add("User-Agent","Mozilla/5.0 (Linux; Android 11; V1981A Build/RP1A.200720.012; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.106 Mobile Safari/537.36;sino-web.com");
        MultiValueMap<String,String> map = new LinkedMultiValueMap();
        params.keySet().forEach(
                key -> map.add(key, params.get(key))
        );
        HttpEntity<MultiValueMap<String,String>> entity = new HttpEntity<>(map, headers);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, entity, clazz);
        return responseEntity.getBody();
    }

    public <T> T postRequest(String url, MediaType mediaType, Map<String,String> params, Class<T> clazz) {
        return postRequest(url, mediaType, params, null, clazz);
    }

}